<?php
/**
*  +----------------------------------------------------------------------------------------------+
*   | Explain:价格
*  +----------------------------------------------------------------------------------------------+
*   | Author: ONLY <491518132@qq.com>
*	+----------------------------------------------------------------------------------------------+
*   | Creater Time : 2013-10-31 	
*  +----------------------------------------------------------------------------------------------+
*   | Link :		http://www.phpyrb.com	     
*  +----------------------------------------------------------------------------------------------+
**/
class PriceAction extends BaseAction {
	protected $product, $newpro;
	protected $auth;
	function _initialize() {
		parent::_initialize ();
		import ( 'Com.Product' );
		import ( 'Com.Newpro' );
		$this->product = new Product ();
		$this->newpro = new Newpro ();
		
		$this->auth=array(14730,16543,11969,11784,13016,11370,15774,16538,16625,16624,16543,11969,16739,12023,1111,102694,102929,102476,15910,104174,18217,103024,105348);
		
	}
	
	/**
	 * (non-PHPdoc)
	 * @see BaseAction::index()
	 */
	function index() {
		$condition = array();
		$prowhere = array();
		$proids = array();
		$_REQUEST ['mname'] = $_REQUEST ['mname'] ? $_REQUEST ['mname'] : 'sj';
		if($_REQUEST ['mname']){
			$prowhere['mname'] = $_REQUEST ['mname'];
			$condition['mname'] = $_REQUEST ['mname'];
		}
		if($_REQUEST['status']){
			$status = $_REQUEST['status'];			
			if($_REQUEST['status'] == 2){
				$status = 0;	
			}
			$prowhere['status'] = $status;
		}
		$prowhere = self::create_where($prowhere);
		
		if($_REQUEST ['brand']){
			$condition['brand'] = $_REQUEST ['brand'];
		}
		if($_REQUEST ['suppliers']){
			$condition['suppliers'] = $_REQUEST ['suppliers'];
		}
	//dump($where);
		//$proids['mname'] = $this->modetopro ( $condition['mname'] );
		
		//获取产品id
		$model = M('Product');
		$res = $model->field('id')->where($prowhere)->select();
		$proids['mname'] = arr2to1($res);
				
		$condition['brand'] ? $proids['brand'] = $this->product->brandtopro($condition['brand'],false) : FALSE;
		$condition['suppliers'] ? $proids['suppliers'] = $this->newpro->supptopro($condition['suppliers']) : FALSE;
// 		dump($proids);
		$proids = $this->newpro->intersection($proids);
		$count = count($proids);
		
		$page = new Page ( $count, $this->listrows );
		$offset = $page->firstRow;
		$length = $page->listRows;
		$proids = array_slice($proids, $offset, $length);
// 		dump($this->listrows);
// 		print_r( $proids );
		$proinfo = $this->newpro->protobaseinfo ( $proids );
		foreach ($proinfo as $key=>$vo){
			$proinfo[$key]['attr'] = $this->product->protoattr($vo['id']);
			$proinfo[$key]['cat'] = $this->product->procat($vo['id']);
		}
		$price = $this->newpro->b2btoprice ( $proids );

		$brand = $this->product->brand(3);
		$suppliers = $this->newpro->suppliers();
		$this->assign ( "totalCount", $count );
		$this->assign ( 'list', $proinfo );
		$this->assign('brand',$brand);
		$this->assign('suppliers',$suppliers);
		$this->assign ( 'price', $price );
		$this->assign('condition',$condition); 
		$this->assign('pstatus',$_REQUEST['status']);
		$this->assign('mname',$_REQUEST['mname']);
		$this->display ();
	}
	
	
	/**
	 * 根据模型名返回产品ID
	 * @param string $_modename 模型名
	 * @param string $_limit 条数
	 * @param string $_count 总数
	 * @param string | int $_status 上下架状态
	 * @return array $proids
	 */
	function modetopro($_modename,$_limit = NULL,$_count = FALSE,$_status = FALSE){
		$model = M('Product');
		$where = array();
		$where['mname'] = $_modename;
		$_status ? $where['status'] = 1: FALSE;
		$where = self::create_where($where);
		if($_count){
			$count = $model->where($where)->count('id');
			echo $model->getLastSql();
			return $count;
		}
		$proids = $model->field('id')->where($where)->limit($_limit)->select();
		// 	 		echo $model->getLastSql();
		// 	 		dump($proids);
		$proids = arr2to1($proids);

		// 	 		dump($proids);
		return $proids;
	}
	
	
	/**
	 *内容管理综合页面
	 *@date 2013-9-17
	 *@time 下午2:43:39
	 */
	function all() {
		//内容管理综合页面
		parent::_cache(1,'cats');
		$this->cats_tree('Price/price');
		$this->display();
	}//end all
	
	
	
	/**
	 *获取分类下的产品
	 *@date 2013-9-17
	 *@time 下午3:40:11
	 */
	function price() {
		
		if (!in_array ( intval($this->userid), $this->auth, true )) {
			$this->_ajm ( 300, '权限不足!', 0);
			exit;
		}
		
		//获取分类下的产品
		$catid=intval($_REQUEST['cid']);
		self::catinfo($catid);
		$where=array();
		if($_REQUEST['status'] ==='1' || $_REQUEST['status'] ==='0'){
			$where['status']=$_REQUEST['status'];			
		}
		if($catid){
			$dao=D("ProductCat");
			$produs = new Product(); 
			$cte = $produs->catetochildren($catid);
			$cte = $produs->arr2to1($cte,'id');
			$where['category_tag_id']= array('IN',implode(',', $cte));
			$this->assign('catid',$catid);
		}else{
			//便于显示无分类产品
			$dao=D("ProductRead");
		}
		//dump($where);
		$where=parent::create_where($where);
		//dump($where);
		$count=$dao->where($where)->count();
		//echo $dao->getlastsql();
		$this->assign("totalCount",$count);
		if($count>0){
			$page=new Page($count,$this->listrows);
			$list=$dao->where($where)->order($this->order)->limit($page->firstRow.','.$page->listRows)->select();
			//echo $dao->getlastsql();
	
			//获取价格
			
			foreach ($list as $key=>$vo){
				$list[$key]['price'] = $vo['price']/100;
				$list[$key]['price_group'] = $this->product->_price_b2b($vo['id'],true);
				//价格日志暂时屏蔽
				//$list[$key]['pricelogs'] = $this->propricelogs($vo['id'],3);
				
				//获取产品货源属性    暂时
				$huoyuan = $this->huoyuan($vo['id']);
				$list[$key]['hoyr'] = $huoyuan['attribute_id'];
				
				$list[$key]['attr'] = $this->product->protoattr($vo['id']);
				$list[$key]['cat'] = $this->product->procat($vo['id']);
			}
			$this->assign('list',$list);
		}
		//print_r($list);
		$status=array();
		$status['0']='下架';
		$status['1']='上架';
		$this->assign('catid',$catid);
		$this->assign('where',$where);
		$this->assign('status',$status);
		$this->display();
	}//end index
	
	
	//获取货源，暂时
	function huoyuan($proid){
		$dao=M('ProductAttribute');		
        $map['product_id'] = $proid;
		$map['attribute_id'] = array('IN',array(170,172,173,174,592)) ;
		$res = $dao->where($map)->field('attribute_id')->find();					
		return $res;
	}
	
	
	/**
	 * 价格日志列表
	 *@date 2013-12-12
	 *@time 下午4:57:17
	 *@author tb
	 */
	function priceloglist(){
		$proids = $_REQUEST['id'];
		if(!$proids){
			$this->_ajm(300,'数据不存在！');
		}
		$count = $this->propricelogs($proids,'all');
		$page=new Page($count,$this->listrows);
		$offset = $page -> firstRow;
		$length = $page -> listRows;
		$list = $this->propricelogs($proids,$offset.','.$length);
		$this->assign('list',$list);
		$this->assign("totalCount",$count);
		$this->display();
	}
	
	/**
	 * 获取价格日志
	 *@date 2013-12-12
	 *@time 下午4:57:17
	 *@author tb
	 */
	function propricelogs($proids,$limit='all'){
		$dao = M('ProductPriceB2bLogs');
		$where['pid'] = is_array($proids) ? array('IN',implode($proids, ',')):$proids;
		if($limit=='all'){
			$count = $dao->where($where)->count();
			return $count;
		}else{
			$res = $dao->where($where)->limit($limit)->order('ctime desc')->select();
			return $res;
		}
	}
	
	
	/**
	 * 返回分类树
	 *@date 2013-6-3
	 *@time 下午4:57:17
	 */
	function cats_tree() {
		//返回分类树
		$cats=F("cats");
		$this->assign("cats",$cats);
		$cats=list_to_tree($cats,'id','parent_id');
		$tree=self::tree($cats);
		$this->assign("tree",$tree);
	}//end cats_tree
	
	
	function tree($arr, $urls = 'Price/price') {
		$str = '';
		foreach ( $arr as $key => $v ) {
			$pid = isset ( $_REQUEST ['pid'] ) ? intval ( $_REQUEST ['pid'] ) : 1;
			$ckd = ($pid == $v ['id']) ? 'myselect="selected"' : '';
			if ($v ['level'] < 10) {
				$str .= "<li " . $ckd . "><a href=\"" . U ( $urls, array (
						"cid" => $v ['id']
				) ) . "\" target=\"ajax\" rel=\"priceBox\">" . $v ['name'] . '</a>';
				if ($v ['_child']) {
					$str .= "<ul>";
					$str .= self::tree ( $v ['_child'] );
					$str .= "</ul>";
				}
			} else {
				$str .= "<li><a href=\"javascript:void(0);\">" . $v ['name'] . '</a>';
			}
			$str .= "</li>";
		}
		return $str;
	}
	
	
	/**
	 *获取分类的信息
	 *@date 2013-9-17
	 *@time 下午2:44:22
	 */
	protected function catinfo($cid=0) {
		//获取分类的信息
		$res=array();
		if($cid==0){
			return $res;
		}
		$dao=D('Cat');
		$catinfo=$dao->info($cid);
		$this->assign('catinfo',$catinfo);
	}//end catinfo
	
	

	/**
	 * ajax 方式修改价格
	 */
	function mjia() {
		$model = M("ProductPriceB2b");
		$id=intval($_POST['id']);
		$catid = $_POST['catid'];
		$data=array();
		$data['price']=$_POST['jia0']*100;
		$data['jiayi']=$_POST['jia1']*100;
		$data['jiaer']=$_POST['jia2']*100;
		$data['jiasan']=$_POST['jia3']*100;
		$data['jiasi']=$_POST['jia4']*100;
		/*if($data['jiayi']<$data['price']){
		 $res=array("ret"=>0,'msg'=>'全国连锁的价格不能小于基价');
		echo json_encode ( $res );
		exit ();
		}*/
		//价格不能为空或为0，如果缺货请操作下架!
		if(!($data['jiayi']&&$data['jiaer']&&$data['jiasan']&&$data['jiasi'])){
			$this->ajaxReturn(2);
		}
		$data['jiawu']=$_POST['jia5']*100;
		$data['jialiu']=$_POST['jia6']*100;
		$data['ctime']=time();
		$param = $data;
		$param['mtime']=time();
		$res=$model->where("product_id='$id'")->save($param);
		if($res){
			//修改主表中的价格。
			$dao = M("Product");
			$dao->where('id='.$id)->save(array('price'=>$param['jiayi']));
	
			//product_price_history 修改价格记录
			$this->price_logs($catid,$id,$data,$this->userid);
	
		}
		if($res>=0){
			$this->ajaxReturn(1);
		}else{
			$this->ajaxReturn(0);
		}
	
	}
	
	
	
	/**
	 * 记录价格更新事件
	 */
	protected function price_logs($mid,$pid,$param,$userid){
		if(empty($mid)||empty($pid)){
			return false;
		}else{
			$dao=M("ProductPriceB2bLogs");
			$data=array();
			$data['mid']=intval($mid);
			$data['pid']=intval($pid);
			$data['mday']=mktime(0,0,0,date("m"),date("d"),date("Y"));
			$data['userid'] = $this->userid;
			//同一个人，同一天，只记录一条数据
			$info=$dao->where($data)->find();
			$data['jiayi']=floatval($param['jiayi']);
			$data['userid']=intval($userid);
			$data['allprice'] = serialize($param);
			if($info){
				$data['ctime']=time();
				$res=$dao->where("id=".$info['id'])->save($data);
			}else{
				$data['ctime']=time();				
				$res=$dao->add($data);
			}
			return $res;
		}
	}
	
	/**
	 * 价格导出
	 */
	function out(){
		if (! in_array ( intval($this->userid), $this->auth, true )) {
			$this->_ajm ( 300, '权限不足!', 0);
			exit;
		}
		$proids = array();
		$proids = $_REQUEST['ids'];
		$proids = explode(',', array_shift($proids));
// 		dump($proids);
// 		exit;
		$proinfo = $this->newpro->b2btoxls($proids);
		$path = $this->newpro->out_xls($proinfo);
// 		dump($path);
// 		exit;
		$this->assign('path',$path);
		$this->display();
	}
	
	function download(){
		$name = $_REQUEST['filename'];
		$path = date ( 'Y-m' ) . '/';
	 	$path = './Downloads/' . $path;
		$this->newpro->downloads($path, $name);
	}
	
	/**
	 * 价格导入模板页
	 * (non-PHPdoc)
	 * @see BaseAction::edit()
	 */
	function edit(){
		if (! in_array ( intval($this->userid), $this->auth, true )) {
			$this->_ajm ( 300, '权限不足!', 0);
			exit;
		}
		$this->display();
	}
	
	/**
	 * (non-PHPdoc)
	 * @see BaseAction::add()
	 */
	function add(){
		$price = array();
		$filePath = '';
		if ($_FILES ['price']['name']) {
			$filePath = $this->_upload ();
			$_SESSION ['file'] = $filePath;
		} else {
			$filePath = $_SESSION ['file'];
		}
		$price = $this->newpro->read_xls($filePath);
// 		dump($price);
// 		exit;
		array_shift($price);
		$data = array();
		$temp = array();
		foreach ($price as $k => $v){
			if($v['10'] > 1){
				if(! empty($v['13'])){
					$temp[$v['0']] = $v;
					$v_t = $v['10']+$v['11'];
					$sale1 = self::setsale($v['10'] , 1);
					$sale2 = self::setsale($v['10'] , 2);
					$data[$v['0']]['price'] = ($v['10']) * 100;
					$data[$v['0']]['jiayi'] = (self::setprice($v['10'] - $sale1)) * 100;
					$data[$v['0']]['jiaer'] = (self::setprice($v['10'] - $sale2)) * 100;
					$data[$v['0']]['jiasan'] = (self::setprice($v_t)) * 100;
					$data[$v['0']]['jiasi'] = (self::setprice($v_t+$v['12'])) * 100;
					$data[$v['0']]['jiawu'] = ($v['11']) * 100;
					$data[$v['0']]['jialiu'] = ($v['12']) * 100;
					$data[$v['0']]['ctime'] = time();
					$data[$v['0']]['status'] = $v['4'] < 1? 0 : $v['15'];
				}
			}
		}
		$_SESSION['checkprice'] = $data;
		$this->assign('plist',$temp);
		$this->display('checkprice');
	}
	
function setsale($price,$type){
	//判断比率
	$sale = 0;
	if($price <0 || $type <0){
		return $sale;
	}
	if($type == 1){
		if($price >=500 && $price<1000){
			$rand = rand(25,30);
			$sale = round($price*$rand*0.001);
		}else if($price >= 1000 && $price < 2000){
			$sale = round($price*2*0.01);
		}else if($price>=2000){
			$sale = round($price*1.5*0.01);
		}
	}else if($type == 2){
		if($price >=500 && $price<1000){
			$rand = rand(15,20);
			$sale = round($price*$rand*0.001);
		}else if($price >= 1000 && $price < 2000){
			$sale = round($price*1.5*0.01);
		}else if($price>=2000){
			$sale = round($price*1*0.01);
		}
	}
	return $sale;
}

function setprice($price){
	 $a = $price%10;
	if($a>0 &&$a<3){
		$price = $price - $a;
	}else if($a>=3 &&$a<=5){
		$price = $price-$a+5;
	}else if($a>5){
		$price = $price-$a +10;
	}
	return $price;
}
	
	/**
	 * 把确定好的价格更新到数据库
	 */
	function checkprice(){
		$price = array();
		$data = array();
		$price = $_SESSION['checkprice'];
		$proids = array_keys($price);
		$mname = $this->manme($proids);
		$plogs = M('ProductPriceB2bLogs');
		$mprice = M('ProductPriceB2b');
		$pstatus = M('Product');
		$mday = $data['mday']=mktime(0,0,0,date("m"),date("d"),date("Y"));
		$ctime = time();
		$reid = false;
		foreach ($price as $k => $v){
			$data['id'] = $k;
			$data['status'] = $v['status'];
			$data['price'] = $v['jiayi'];
			$data['write_date'] = time();
// 			$reid = $mprice->where(array('product_id'=>$k))->save($v);
 			$reid = $pstatus->save($data);
			unset($v['status']);
			//价格日志写入
			//unset( $v['ctime']);
			M('product_price_b2b')->where(array('product_id'=>$k))->save($v);
			$logs = array();
			$logs['allprice'] = serialize($v);
			$logs['pid'] = $k;
			$logs['jiayi'] = $v['jiayi'];
			$logs['ctime'] = $ctime;
			$logs['mday'] = $mday;
			$logs['mname'] = $mname[$k]['mname'];
			$logs['userid'] = $_SESSION['userid'];
			$reid = $plogs->add($logs);
		}
		if($reid){
			$this->success('更新成功！',U('Price/index'));
			exit;
		}else{
			$this->error('更新成功！',U('Price/index'));
		}
	}
	
	/**
	 * 返回模型名称
	 * @param array $_prodis
	 * @return  array $mname
	 */
	function manme($_prodis){
		$model = M('Product');
		$where = array();
		$where['id'] = is_array($_prodis) ? array("IN",implode(',', $_prodis)) : $_prodis;
		$mname = $model->field('id,mname')->where($where)->select();
		$mname = field2key($mname,'id');
		return $mname;
	}
	
	/**
	 * 处理文件上传
	 * @return string
	 */
	function _upload() {
		// $upfile=F('upfile');
		import ( "Com.UploadFile" );
		$upload = new UploadFile ();
		// 设置上传文件大小
		$upload->maxSize = 3292200;
		// 设置上传文件类型
		$upload->allowExts = explode ( ',', 'xls,xlsx,jpg' );
		// 设置附件上传目录
		$path = date ( 'Y-m' ) . '/';
		$upload->savePath = './Uploads/' . $path;
		if(! file_exists( $upload->savePath)){
			if(! mkdir ( $upload->savePath)){
				echo '创建文件夹失败！';
				exit;
			}
		}
		$path = 'Uploads/' . $path;
		// 设置需要生成缩略图，仅对图像文件有效
		// 设置上传文件规则
		$upload->saveRule = 'time';
		$upload->uploadReplace = true;
		if (! $upload->upload ()) {
			// 捕获上传异常
			$this->error ( $upload->getErrorMsg () );
		} else {
			// 取得成功上传的文件信息
			$uploadList = $upload->getUploadFileInfo ();
			$_POST ['picurl'] = $path . $uploadList [0] ['savename'];
		}
		return $_POST ['picurl'];
	}
	
	function w_price_logs($_data){
		$model = M('ProductPriceB2bLogs');
		$data = array();
		foreach ($_data as $k => $v){
			
		}
	}
	
	function update_(){
		$map = array( 'id'=>$_REQUEST['id'],'sequence'=>$_REQUEST['sque'] );
		echo M('product')->save($map);
		die();
	}
	function updatestock(){
		if(!$_REQUEST['stock']<-1){
			$map = array( 'id'=>$_REQUEST['id'],'stock'=>$_REQUEST['stock'] );
			echo M('Product')->save($map);
		}
		die();
	}
	
	function ajax_minsale(){
		$map = array( 'product_id'=>$_REQUEST['id'],'minsale'=>$_REQUEST['minsale'] );
		echo M('ProductPriceB2b')->where('product_id='.$_REQUEST['id'])->save($map);
		die();
	}
	/**
	 * 库存导入模板页
	 * (non-PHPdoc)
	 * @see BaseAction::edit()
	 */
	function repertory(){
		if (! in_array ( intval($this->userid), $this->auth, true )) {
			$this->_ajm ( 300, '权限不足!', 0);
			exit;
		}
		$this->display();
	}
	/**
	 * 更新库存
	 */
	function update_repertory(){
		$repertory = array();
		$filePath = '';
// 		if ($_FILES ['price']['name']) {
			$filePath = $this->_upload ();
// 			$_SESSION ['file'] = $filePath;
// 		} else {
// 			$filePath = $_SESSION ['file'];
// 		}
		$repertory = $this->newpro->read_xls($filePath);
		array_shift($repertory);
		$data = array();
		$pstatus = M('Product');
		foreach ($repertory as $v){
			if($v['5'] < 0 && $v['4'] < 0){
				$data['stock'] = -1;
				$data['write_date'] = time();
				$reid = $pstatus->where(array('id'=>$v['0']))->save($data);
			}elseif($v['5'] >= 0){
				$data['stock'] = $v['5'];
				if($v['6'] > -1){
					$data['status'] = $v['6'];
				}
				$data['write_date'] = time();
				$reid = $pstatus->where(array('id'=>$v['0']))->save($data);
			}elseif ($v['4'] >= 0){
				$data['stock'] = $v['4'];
				if($v['6'] > -1){
					$data['status'] = $v['6'];
				}
				$data['write_date'] = time();
				$reid = $pstatus->where(array('id'=>$v['0']))->setInc('stock',$v['4']);
			}
		}
		echo '更新完成';
	}
	/**
	 * 更新云购状态
	 */
	function update_ygstatus(){
		$sql="UPDATE product SET ygstatus = status";
		M()->query($sql);
		$sql="UPDATE product SET ygstatus = 1 where id in (
		select * from (
		select DISTINCT p.id from product p
		LEFT JOIN order_goods g on g.product_id = p.id
		LEFT JOIN `order` o ON o.id=g.order_id
		where FROM_UNIXTIME(o.add_time,'%Y%m%d')>20140216 and p.price > 0) pro)";
		$res=M()->query($sql);
		if($res===FALSE){
			$this->_ajm(300,'操作失败，请重新操作！');
		}else{
			$this->_ajm ( 200, '操作成功', 1);
		}
	}
	/**
	 * 采购统计
	 */
	function procurement_statistics(){
		if($_REQUEST['starttime'] && $_REQUEST['endtime']){
			$starttime = gettime($_REQUEST['starttime']." 00:00:00");
			$endtime = gettime($_REQUEST['endtime']." 23:59:59");
		}
		$list=M()->query("select FROM_UNIXTIME(o.add_time,'%m月%d日') add_time,o.sn sn,(CASE og.mname WHEN 'sj' THEN '手机' 
				WHEN 'pb' THEN '平板' ELSE '手机配件' END) as mname,og.product_name product_name,
				og.number number,og.price price,og.priceall priceall,oc.`value` BV,og.priceall priceall,'库存' as gys
				from `order` o LEFT JOIN order_goods og on o.id = og.order_id LEFT JOIN order_coupon oc on o.id = oc.order_id and oc.goods_id = og.product_id 
				WHERE o.add_time> $starttime AND o.add_time< $endtime order by o.id,og.product_id");
		$this->assign('starttime',$_REQUEST['starttime']);
		$this->assign('endtime',$_REQUEST['endtime']);
		$this->assign('type',$_REQUEST['type']);
		$this->assign('list',$list);
		$this->display();
	}
	
}